package com.huangmingfu;

/**
 * @Author: 黄名富
 * @Description: 状态模式
 * @需求描述: 银行卡有三种状态、正常、透支、限制。 正常状态下可以取钱、存钱。 透支情况下，每次取钱额度不超过500，
 * 限制情况下只能存钱。 余额 >= 0 正常， -1000 <= 余额 < 0 透支，余额 < 1000 限制
 */
public class StatePattern {

    public static void main(String[] args) {
        BackCard backCard = new BackCard();
        backCard.save(100);
        backCard.withdraw(1000);
        backCard.withdraw(600);
        backCard.withdraw(400);
        backCard.withdraw(100);
    }

    private static class BackCard {

        private final static State[] stateList = {new NormalState(),new Overdraft(),new LimitState()};

        private State state = stateList[0];

        private double balance = 0;

        public double getBalance() {
            return balance;
        }

        public void setBalance(double balance) {
            this.balance = balance;
        }

        public void save(double money) {
            System.out.println("存钱操作:" + money);
            this.balance += money;
            changeState();
        }

        public void withdraw(double money) {
            System.out.println("取钱操作:" + money);
            try {
                state.withdraw(this,money);
            } catch (RuntimeException e) {
                System.out.println("取钱失败:" + e.getMessage());
            }
            changeState();
        }

        private void changeState() {
            System.out.println("-----余额：" + balance + "-----");
            if (balance >= 0) state = stateList[0];
            else if (balance >= -1000) state = stateList[1];
            else state = stateList[2];
        }

    }

    private interface State {
        void withdraw(BackCard backCard,double money);
    }

    private static class NormalState implements State {
        @Override
        public void withdraw(BackCard backCard,double money) {
            backCard.setBalance(backCard.getBalance() - money);
        }
    }

    private static class Overdraft implements State {
        @Override
        public void withdraw(BackCard backCard,double money) {
            if (money > 500) {
                throw new RuntimeException("卡被透支，取钱不能超过500元");
            }
            backCard.setBalance(backCard.getBalance() - money);
        }
    }

    private static class LimitState implements State {
        @Override
        public void withdraw(BackCard backCard,double money) {
            throw new RuntimeException("卡被限制，不能取钱");
        }
    }



}
